package com.kent.internet;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * Notice: 向web站点发送GET请求、post请求，并从web站点取得响应。
 *
 * @author kent_sun
 * @version 1.0
 * @date 2021/5/1
 * @since 1.0
 */
public class GetPostTest {

    public static String sendGet(String url, String param) {
        String result = "";
        String urlName = url + "?" + param;
        try {
            var realUrl = new URL(urlName);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0");
            // 建立实际的连接
            conn.connect();
            // 获取所有的响应头字段
            Map<String, List<String>> map = conn.getHeaderFields();
            for (var key : map.keySet()) {
                System.out.println(key + "----->" + map.get(key));
            }
            try (
                    // 定义BufferedReader输入流来读取URL响应
                    var in = new BufferedReader(
                            new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                String line;
                while ((line = in.readLine()) != null) {
                    result += "\n" + line;
                }
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 发送post请求
     *
     * @param url   请求地址
     * @param param 参数，格式应满足： name1=value&name2=value2
     * @return URL代表远程资源的响应
     */
    public static String sendPost(String url, String param) {
        String result = "";
        try {
            var readUrl = new URL(url);
            URLConnection conn = readUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0");
// 发送post请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            try (
                    // 获取URLConnection对象对应的输出流
                    var out = new PrintWriter(conn.getOutputStream())
            ) {
                // 发送请求参数
                out.print(param);
                // flush输出流的缓冲
                out.flush();
            }
            try (
                    // 定义
                    var in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            ) {
                String line;
                while ((line = in.readLine()) != null) {
                    result += "\n" + line;
                }
            }
        } catch (Exception e) {
            System.out.println("发送POST请求出现异常！" + e);
            e.printStackTrace();
        }
        return result;
    }

    // 提供主方法， 测试发送GET请求和POST请求
    public static void main(String[] args) {
        // 发送GET请求
        String s = GetPostTest.sendGet("https://www.baidu.com/s", "ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=java&fenlei=256");
        System.out.println(s);
        // 发送post请求
        // String s1 = GetPostTest.sendPost("http://localhost:8888/abc/login.jsp", "name=crazyit.org&pass=leegang");
        // System.out.println(s1);
    }
}
